﻿using Microsoft.SharePoint;
using SP.Exporters;
using System;
using System.Globalization;
using System.IO;

namespace SP.ListItem.WordExporter.Utils
{
    public static class SPExtensions
    {
        /// <summary>
        /// Ensures such list exists in the web.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="listTitle">The list title.</param>
        /// <param name="description">The description.</param>
        /// <param name="template">The template.</param>
        /// <returns></returns>
        public static SPList EnsureList(this SPWeb web,string listTitle,string description,SPListTemplateType template){
            var list = web.Lists.TryGetList(listTitle);
            if (list == null)
            {
              var listId = web.Lists.Add(listTitle, description, template);
              list = web.Lists[listId];
            }
            return list;
        }

        /// <summary>
        /// Ensures the field is associated with the list.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="fieldInternalName">Name of the field internal.</param>
        /// <returns></returns>
        public static SPField EnsureField(this SPList list, string fieldInternalName)
        {
            if(!list.Fields.ContainsField(fieldInternalName))
            {
                var field = list.ParentWeb.AvailableFields.GetFieldByInternalName(fieldInternalName);
                list.Fields.Add(field);
                list.Update();
            }
            return list.Fields.GetFieldByInternalName(fieldInternalName);
        }

        /// <summary>
        /// Gets the word exporter template file.
        /// </summary>
        /// <param name="web">The web.</param>
        /// <param name="sourceListTitle">The source list title.</param>
        /// <returns></returns>
        /// <exception cref="WordExporterException">
        /// </exception>
        public static SPFile GetWordExporterTemplateFile(this SPWeb web, string sourceListTitle)
        {
            var templatesLibrary = web.Lists.TryGetList(Constants.Lists.Templates);
            if (templatesLibrary == null)
            {
                throw new WordExporterException(String.Format(CultureInfo.InvariantCulture, "Word Exporter Templates Library was not found in site {0}", web.Url));
            }
            var query = new SPQuery
                {
                    Query =
                        String.Format(CultureInfo.InvariantCulture,
                                      "<Where><Eq><FieldRef Name='{0}' /><Value Type='Text'>{1}</Value></Eq></Where><OrderBy><FieldRef Name='Created'></FieldRef></OrderBy>",
                                      Constants.Fields.TemplatesListTitle, sourceListTitle)
                };
            var templateItems = templatesLibrary.GetItems(query);
            if (templateItems.Count == 0)
            {
                throw new WordExporterException(String.Format(CultureInfo.InvariantCulture, "No Word Exporter template was not found in site {0} for list {1}", web.Url, sourceListTitle));
            }
            // take the first found template
            var templateFile = templateItems[0].File;
            if (templateFile == null)
            {
                throw new WordExporterException(String.Format(CultureInfo.InvariantCulture, "The associated template for this list is corrupt in site {0}. Please contact your administrator", web.Url));
            }
            return templateFile;
        }

        /// <summary>
        /// Generates the word export file.
        /// </summary>
        /// <param name="item">The item.</param>
        /// <param name="templateFile">The template file.</param>
        /// <returns></returns>
        public static Stream GenerateWordExportFile(this SPListItem item, SPFile templateFile)
        {
            var exporter = new ListItemWordExporter(item, templateFile);
            return exporter.Export();
        }

    }
}
